package com.jt.auth.service.impl;

import com.jt.auth.service.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.基于用户获取远端服务的用户信息
        com.jt.auth.pojo.User user = remoteUserService.selectUserByUsername(username);
        if (user==null)
            throw new UsernameNotFoundException("user not found");
        //2.基于远端用户id获取用户权限信息
        List<String> permissions = remoteUserService.selectUserPermissions(user.getId());
        log.debug("user.permissions:{}",permissions);
        //3.封装用户信息并返回,交给认证管理器对用户身份进行认证.

        return new User(username,user.getPassword(), AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));
    }
}
